package com.xinqi.modules.databank.v2.service.question.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinqi.common.base.response.R;
import com.xinqi.common.base.utils.spring.Spring;
import com.xinqi.common.core.enums.ClassRoleEnum;
import com.xinqi.common.core.enums.CourseContentTypeEnum;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.databank.dto.req.CourseResourceQuestionCreateDTO;
import com.xinqi.modules.databank.dto.req.CourseResourceQuestionQueryDTO;
import com.xinqi.modules.databank.dto.rsp.QuizResultDTO;
import com.xinqi.modules.databank.remind.ChatRemindService;
import com.xinqi.modules.databank.v2.convert.CourseResourceQuestionConvert;
import com.xinqi.modules.databank.v2.domain.CourseResourceQuestionEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourceQuestionGiveEntity;
import com.xinqi.modules.databank.v2.manager.ResourceQuestionGiveManager;
import com.xinqi.modules.databank.v2.manager.ResourceQuestionManager;
import com.xinqi.modules.databank.v2.service.question.ResourceQuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 资料库提问-业务层
 * @author dzy
 */
@Service
@RequiredArgsConstructor
public class ResourceQuestionServiceImpl implements ResourceQuestionService {

    private final CourseResourceQuestionConvert resourceQuestionConvert;
    private final ResourceQuestionManager resourceQuestionManager;

    private final ResourceQuestionGiveManager resourceQuestionGiveManager;

    private final ClassStudentClient classStudentClient;

    private final ChatRemindService chatRemindService;

    /**
     * 添加提问
     * @author dzy
     */
    @Override
    public QuizResultDTO addQuiz(CourseResourceQuestionCreateDTO create) {
        create.setTouid(0L);
        create.setPid(0L);
        create.setTpid(0L);
        Long userId = LoginHelper.getUserId();
        create.setUid(userId);

        // 赋值操作用户身份
        this.setOperaRelationship(create);

        CourseResourceQuestionEntity entity = resourceQuestionConvert.create(create);
        resourceQuestionManager.save(entity);
        QuizResultDTO resultQuiz = resourceQuestionManager.selectQuizById(entity.getId(), entity.getClassId(), userId);
        Spring.committedAsync(() -> {
            chatRemindService.questionChatRemind(LoginHelper.getXqLoginUser(), CourseContentTypeEnum.DATA, entity);
        });
        return resultQuiz;
    }

    /**
     * 添加提问-回复
     * @author dzy
     */
    @Override
    public QuizResultDTO replyQuiz(CourseResourceQuestionCreateDTO create) {
        CourseResourceQuestionEntity parentQuiz = resourceQuestionManager.getById(create.getPid());
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(parentQuiz), "提问不存在");

        if (parentQuiz.getTpid() == 0) {
            create.setTpid(parentQuiz.getId());
        } else {
            create.setTpid(parentQuiz.getTpid());
        }
        create.setPid(parentQuiz.getId());
        create.setTouid(parentQuiz.getUid());
        Long userId = LoginHelper.getUserId();
        create.setUid(userId);
        create.setId(null);

        // 赋值操作用户身份
        this.setOperaRelationship(create);

        CourseResourceQuestionEntity entity = resourceQuestionConvert.create(create);
        resourceQuestionManager.save(entity);

        QuizResultDTO resultQuiz = resourceQuestionManager.selectQuizById(entity.getId(), entity.getClassId(), userId);

        Spring.committedAsync(() -> {
            chatRemindService.replyChatRemind(LoginHelper.getXqLoginUser(), CourseContentTypeEnum.DATA, entity);
        });

        return resultQuiz;
    }

    /**
     * 赋值操作用户身份
     * @author dzy
     */
    private void setOperaRelationship(CourseResourceQuestionCreateDTO create) {
        Long userId = LoginHelper.getUserId();
        // 获取用户信息
        ClassStudentResultDTO student = R.as(classStudentClient.findByStudentId(create.getClassId(), userId));
        // 获取主学生信息
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(create.getClassId(), userId));
        if (Objects.nonNull(mainStudent)) {
            create.setStudentName(mainStudent.getStudentName());
            create.setOperaRelationship(student.getRelationship());
        } else {
            if (Objects.equals(ClassRoleEnum.TEACHER.getCode(), student.getClassRole())) {
                create.setOperaRelationship(ClassRoleEnum.TEACHER.getDescribe());
            } else if (Objects.equals(ClassRoleEnum.ASSISTANT.getCode(), student.getClassRole())) {
                create.setOperaRelationship(ClassRoleEnum.ASSISTANT.getDescribe());
            }
        }
    }

    /**
     * 获取提问-列表
     * @author dzy
     */
    @Override
    public PageInfo<QuizResultDTO> selectQuiz(CourseResourceQuestionQueryDTO queryDTO) {
        Long userId = LoginHelper.getUserId();
        IPage<QuizResultDTO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        queryDTO.setPid(0L);
        queryDTO.setUserId(userId);
        IPage<QuizResultDTO> resultsPage = resourceQuestionManager.selectQuiz(page, queryDTO);
        resultsPage.getRecords().forEach(item -> {
            if (item.getPcount() > 0) {
                CourseResourceQuestionQueryDTO queryDTO1 = new CourseResourceQuestionQueryDTO();
                IPage<QuizResultDTO> page2 = new Page<>(1, 3);
                queryDTO1.setTPid(item.getId());
                queryDTO1.setClassId(item.getClassId());
                queryDTO1.setUserId(userId);
                IPage<QuizResultDTO> sonPage = resourceQuestionManager.selectQuiz(page2, queryDTO1);
                item.setChildren(sonPage.getRecords());
            }
        });
        PageInfo<QuizResultDTO> pageInfo = Pages.convert(resultsPage);
        return pageInfo;
    }

    /**
     * 获取提问-子列表
     * @author dzy
     */
    @Override
    public PageInfo<QuizResultDTO> selectSonQuiz(CourseResourceQuestionQueryDTO queryDTO) {
        Long userId = LoginHelper.getUserId();
        queryDTO.setUserId(userId);
        IPage<QuizResultDTO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        IPage<QuizResultDTO> sonPage = resourceQuestionManager.selectQuiz(page, queryDTO);
        PageInfo<QuizResultDTO> pageInfo = Pages.convert(sonPage);
        return pageInfo;
    }

    /**
     * 提问-删除
     * @author dzy
     */
    @Override
    public void removeQuiz(Long id) {
        resourceQuestionManager.deleteById(id);
    }

    /**
     * 提问-点赞
     * @author dzy
     */
    @Override
    public void give(Long id) {
        CourseResourceQuestionEntity questionEntity = resourceQuestionManager.getById(id);
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(questionEntity), "未获取到提问信息");

        Long userId = LoginHelper.getUserId();
        LambdaQueryWrapper<CourseResourceQuestionGiveEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseResourceQuestionGiveEntity::getUserId, userId);
        wrapper.eq(CourseResourceQuestionGiveEntity::getComId, id);
        CourseResourceQuestionGiveEntity giveEntity = resourceQuestionGiveManager.getOne(wrapper);
        if (Objects.nonNull(giveEntity)) {
            resourceQuestionGiveManager.deleteById(giveEntity.getId());
            return;
        }
        giveEntity = new CourseResourceQuestionGiveEntity();
        giveEntity.setUserId(userId);
        giveEntity.setComId(id);
        resourceQuestionGiveManager.save(giveEntity);

        Spring.committedAsync(() -> {
            chatRemindService.giveChatRemind(LoginHelper.getXqLoginUser(), CourseContentTypeEnum.DATA, questionEntity);
        });

    }

}
